<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\ImportExportEvent;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\Clothes;
use App\Models\V1\ClotheSize;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
USE Log;
use Auth;

class ClotheExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入课程数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校服数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }

            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(7);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'code' => $item[0],
                        'name' => $item[1],
                        'picture' => $item[1],
                        'remark' => $item[3],
                        'count' => $item[4],
                        'unit' => $item[5],
                        'sex_limit' => $item[6],
                    ];
                    if (!empty($item[0]) && !empty($item[1])) {
                        Clothes::updateOrCreate(['arrival_code'=>$item[0],'code'=>$item[1]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }


    /***
     * @param ImportDataRequest $request
     * @return $this
     */
    public function importSizeData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校服尺码数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }

            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(8);
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'cloth_code' => $item[0],
                        'code' => $item[1],
                        'name' => $item[2],
                        'height_low' => $item[3],
                        'height_high' => $item[4],
                        'size' => $item[5],
                        'cloth_length' => $item[6],
                        'bust' => $item[7],
                    ];
                    if (!empty($item[0]) && !empty($item[1])) {
                        ClotheSize::updateOrCreate(['code'=>$item[1]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出校服数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

//        $header = ['迎新代码', '校服代码', '校服名称','校服图片', '校服备注', '人均校服数量','数量单位','性别限制'];
        $header = ['校服代码', '校服名称','校服图片', '校服备注', '人均校服数量','数量单位','性别限制（1:男女不限  2：男生领用  3: 女生领用）'];
        $arrival_code = $this->getArrivalCode();
        if (empty($arrival_code)) {
            $response['rspStatus'] = false;
            $response['rspMsg'] = '请先启动迎新换届';
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
        $custodian = Clothes::where('arrival_code',$arrival_code)->select('code','name','picture','remark','count','unit','sex_limit')->get();
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->picture,
                $item->remark,
                $item->count,
                $item->unit,
                $item->sex_limit,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','校服'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('cloth', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[校服]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header1 = [ '校服代码', '校服名称', '校服图片','校服备注', '人均校服数量','数量单位','性别限制（1:男女不限  2：男生领用  3: 女生领用）'];
        $cellDatas1 = [$header1];
        $cellData1 = ['cl10001','三件套西装','','请仔细检查有无损坏',2,'套',2];
        $cellData2 = ['cl10002','正装','','',1,'套',1];
        array_push($cellDatas1, $cellData1);
        array_push($cellDatas1, $cellData2);

        $header2 = [ '校服代码', '尺寸代码', '尺寸名称','适合最低身高(cm)', '适合最高身高(cm)','尺寸大小','衣长','胸围'];
        $cellDatas2 = [$header2];
        $cellData3 = ['cl10001','size000001','S码','160','165','80','75','80'];
        $cellData4 = ['cl10002','size000002','M码','165','170','82','76','82'];
        array_push($cellDatas2, $cellData3);
        array_push($cellDatas2, $cellData4);

        Excel::create('校服与校服尺码数据导入模版', function ($excel) use ($cellDatas1,$cellDatas2, $clientIP) {
            $excel->sheet('cloth', function ($sheet) use ($cellDatas1) {
                $sheet->rows($cellDatas1);
            });
            $excel->sheet('clothsize', function($sheet) use ($cellDatas2){
                $sheet->rows($cellDatas2);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[校服与校服尺码]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
